package com.neusoft.bootweb.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class FileUploadController {

    @RequestMapping("/fileup.do")
    @ResponseBody
    public String getFile(HttpServletRequest request
            , MultipartFile multipartFile)
    {
        if(!multipartFile.isEmpty())
        {
            //String path = request.getServletContext().getRealPath("/upload/");
            //File newfile = new File(multipartFile.getOriginalFilename());
            try {
                multipartFile.transferTo(new File(multipartFile.getOriginalFilename()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "上传成功！！！";
        }
        return "上传失败";
    }


    @RequestMapping("/fileDown.do")
    public ResponseEntity<byte[]> downFilesss(/*@RequestHeader("User-Agent") String userAgent */ )
            throws IOException {
        System.out.println("下载");
        String filepath = "D:\\aaa\\前端试卷-FY18_武汉_社会个体_Java7班汇总成绩5388886481624158329.xls";
        File file = new File(filepath);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(FileUtils.readFileToByteArray(file));
    }

    @RequestMapping("/aaa.do")
    @ResponseBody
    public String getaaa()
    {
        return "ok";
    }
}
